/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.CommonUtil;
import Common.Global;
import DAO.AccountDAO;
import DAO.NotificationDAO;
import hibernate.entity.Account;
import hibernate.entity.Notification;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author NamDH
 */
public class LoginSignupController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        try {
            String login = request.getParameter("action");
            if (login.equals("Login")) {
                String isExtension = "";
                if (request.getParameter("isExtension") != null) {
                    isExtension = request.getParameter("isExtension");
                }
                session.removeAttribute("GETPASSWORD");
                session.removeAttribute("CHANGEPASSWORD");
                String accountEmail = request.getParameter("email");
                String password = request.getParameter("password");
                String convertPassword = CommonUtil.md5(password);
                AccountDAO accDAO = new AccountDAO();
                Account acc = accDAO.checkAccountByPassword(accountEmail, convertPassword);
                if (acc != null) {
                    boolean active = acc.isActive();
                    boolean emailVerify = acc.getEmailVerify();
                    if (active == true && emailVerify == true) {
                        int accID = acc.getAccountID();
                        session.setAttribute("LOGINID", accID);
                        session.setAttribute("LOGINEMAIL", accountEmail);
                        session.setAttribute("ACCOUNT", acc);
                        String url = Common.Global.homepage;
                        if (isExtension.equals("true")) {
                            url = "HomeController?btAction=ExTrack";
                        }
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    } else {
                        request.setAttribute("BANNEDUSER", "You are banned or email is not verified!!!");
                        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
                        rd.forward(request, response);
                    }
                } else {
                    request.setAttribute("LOGINFAIL", "Your password or email is wrong!!!");
                    RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                    rd.forward(request, response);
                }
            } else if (login.equals("Register")) {
                int roleID = 3;
                String emailAddress = request.getParameter("txtRegisterEmailAddress");
                String username = request.getParameter("txtRegisterUsername");
                String password = request.getParameter("txtRegisterPassword");
                AccountDAO checkAccDAO = new AccountDAO();
                Account checkAcc = checkAccDAO.checkEmail(emailAddress);
                if (checkAcc == null) {
                    String convertPassword = CommonUtil.md5(password);
                    boolean active = false;
                    boolean EmailVerify = false;
                    AccountDAO accDAO = new AccountDAO();
                    NotificationDAO noDAO = new NotificationDAO();
                    int accID = accDAO.register(roleID, emailAddress, username, convertPassword, active, EmailVerify);
                    for (int i = 1; i < 3; i++) {
                        noDAO.insertNotification(accID, i);
                    }
                    StringBuffer requestURL = request.getRequestURL();
                    if (request.getQueryString() != null) {
                        requestURL.append("?").append(request.getQueryString());
                    }
                    String URL = requestURL.toString();
                    String endContent = "\n\nHave a nice day and hard working.\nRegards,\n\nContact support: capstonePRTS@gmail.com\nPhone number: 01699565879\nAddress: FPT, F-Town building, High-tech park, District 12, Ho Chi Minh City, Viet Nam\nWorking time: 8h30AM~9h30PM everyday (except Saturday and Sunday)";
                    String urlVerify = "Your account's almost ready!\nPlease click here to verify email\n" + URL + "?action=verifyEmail&accEmail=" + emailAddress + "&verify=" + convertPassword + endContent;
                    //dang fix cung cho nay ve cai subject
                    CommonUtil.sendEmail(emailAddress, urlVerify, "[PRTS]Verify email!");
                    request.setAttribute("REGISTERSUCCESS", "Please check your email to verify your account!!!");
                    RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                    rd.forward(request, response);
                } else if (checkAcc != null) {
                    request.setAttribute("DUPLICATEEMAIL", "Someone already has that username. Try another?");
                    RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                    rd.forward(request, response);
                }
            } else if (login.equals("GetPassword")) {
                session.setAttribute("GETPASSWORD", out);
                response.sendRedirect(Common.Global.loginpage);
            } else if (login.equals("Close")) {
                session.removeAttribute("GETPASSWORD");
                response.sendRedirect(Common.Global.loginpage);
            } else if (login.equals("getPass")) {
                String email = request.getParameter("txtGetEmail");
                String username = request.getParameter("txtGetUsername");
                AccountDAO accDAO = new AccountDAO();
                Account acc = accDAO.checkAccountByUsername(email, username);
                if (acc != null) {
                    String newPasword = CommonUtil.makeNewPassword();
                    boolean sendEmail = CommonUtil.sendEmail(email, newPasword);
                    if (sendEmail == true) {
                        String convertNewPassword = CommonUtil.md5(newPasword);
                        int accountID = acc.getAccountID();
                        boolean checkChange = accDAO.changePassword(convertNewPassword, accountID);
                        if (checkChange) {
                            request.setAttribute("GETPASSSUCCESS", "Your password is sent to your email!!!");
                            RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                            rd.forward(request, response);
                        } else {
                            request.setAttribute("GETPASSEXCEP", "Sorry but your password can't be changed!!!");
                            RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                            rd.forward(request, response);
                        }
                    } else {
                        request.setAttribute("GETPASSFAIL", "Password can't be sent to your email!!!");
                        RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                        rd.forward(request, response);
                    }
                } else {
                    request.setAttribute("GETFAIL", "Your email or full name is wrong!!!");
                    RequestDispatcher rd = request.getRequestDispatcher(Common.Global.loginpage);
                    rd.forward(request, response);
                }
            } else if (login.equals("verifyEmail")) {
                String email = request.getParameter("accEmail");
                String verify = request.getParameter("verify");
                AccountDAO accDao = new AccountDAO();
                Account account = accDao.getAccountByEmail(email);
                if (account.getPassword().equals(verify)) {
                    accDao.updateActive(true, account.getAccountID());
                    accDao.updateEmailVerify(true, account.getAccountID());
                    session.setAttribute("ACCOUNT", account);
                    response.sendRedirect(Global.homepage);
                } else {
                    response.sendRedirect(Global.loginpage);
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
